package com.ruoyi.quartz.task;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.NurseLeave;
import com.ruoyi.system.mapper.NurseLeaveMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 护理人员状态定时更新
 */
@Component("nurseStatusTask")
public class NurseStatusTask {

    private static final Logger log =  LoggerFactory.getLogger(NurseStatusTask.class);

    @Resource
    private NurseLeaveMapper nurseLeaveMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    public void updateNurseStatus() {
        log.info("护理人员状态定时更新开始");
        // 查询所有护理人员
        SysUser sysUser = new SysUser();
        sysUser.setDelFlag("0");
        List<SysUser> sysUsers = sysUserMapper.selectNurseList(sysUser);

        Set<Long> collect = sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toSet());
        // 查询所有审核通过的护士请假信息
        NurseLeave nurseLeave = new NurseLeave();
        nurseLeave.setNurseIds(collect);
        nurseLeave.setStatus("1");
        List<NurseLeave> nurseLeaves = nurseLeaveMapper.selectNurseLeaveList(nurseLeave);
        if (nurseLeaves.isEmpty()){
            log.info("没有护理员请假信息");
            return;
        }
        Date now = new Date();
        Map<Long, List<NurseLeave>> collect1 =
                nurseLeaves.stream().collect(Collectors.groupingBy(NurseLeave::getNurseId));
        for (SysUser user : sysUsers) {
            //先设定 没请假状态
            user.setLeaveStatus("0");
            List<NurseLeave> nurseLeaves1 = collect1.get(user.getUserId());
            if (nurseLeaves1 != null && !nurseLeaves1.isEmpty()){
                for (NurseLeave leave : nurseLeaves1) {
                    if (now.compareTo(leave.getStartTime()) >= 0 && now.compareTo(leave.getEndTime()) <= 0){
                        user.setLeaveStatus("1");
                        break;
                    }
                }
            }
            sysUserMapper.updateUser(user);
        }
        log.info("护理员请假状态 更新完成");

    }
}
